<style scoped>
.filter-bar {
    /* display: flex; */
    justify-content: flex-start;
    align-items: center;
    margin: 8px 0 8px 0;
}
.filter-label {
    margin-right: 6px;
    color: #606266;
    font-size: 14px;
    white-space: nowrap;
}
.filter-date-picker {
    width: 260px;
    margin-right: 8px;
    --el-date-editor-height: 32px;
}
.filter-btn {
    height: 32px;
    padding: 0 16px;
    margin-right: 6px;
    font-size: 14px;
    
    border-radius: 4px;
    box-sizing: border-box;

    align-items: center;
}
.filter-btn:last-child {
    margin-right: 0;
}
.chart-title {
    text-align: center;
    margin: 20px 0 10px 0;
    font-size: 20px;
    font-weight: bold;
}
.chart-container {
    display: flex;
    justify-content: flex-start;
    width: 100%;
}
.echart {
    width: 100%;
    height: 400px;
}
.tag-list-container {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
}
.total-count {
    text-align: center;
    margin: 10px 0;
    font-size: 14px;
    color: #606266;
}
</style> 

<template>
  <div>
    <div class="filter-bar">
      <span class="filter-label">创建时间</span>
      <el-date-picker
        v-model="dateRange"
        type="datetimerange"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        width = 260
        class="filter-date-picker"
        value-format="YYYY-MM-DD HH:mm:ss"
      />
      <el-button type="primary" class="filter-btn" @click="handleSearch">
        <el-icon style="margin-right: 4px;"><Search /></el-icon>
        搜索
      </el-button>
      <el-button @click="onReset" class="filter-btn">
        <el-icon style="margin-right: 4px;"><Refresh /></el-icon>
        重置
      </el-button>
    </div>
    <div style="display: flex; justify-content: center; align-items: center; margin-bottom: 10px;">
      <h2 class="chart-title" style="margin-bottom: 0;">活动总数分析</h2>
      <!-- <el-button type="text" style="color: #409EFF; border: none; background: none;">更多</el-button> -->
    </div>
    <div class="chart-container">
      <div ref="chartRef" class="echart"></div>
    </div>
    <div style="display: flex; justify-content: center; align-items: center; margin-bottom: 10px;">
      <h2 class="chart-title" style="margin-bottom: 0;">活动有效率分析</h2>
  
    </div>
    <div class="chart-container">
      <div ref="chartRef2" class="echart"></div>
    </div>
   

    <div class="tag-list-container">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="name" label="活动名称" width="180" />
        <el-table-column prop="count" label="线索数量" width="180" />
        <el-table-column prop="available" label="线索有效率" />
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { getToken } from '../../../utils/auth'
import type { Ref } from 'vue'
import type { EChartsType } from 'echarts'
import { getActivityAnalysis } from '../../../api/tienchin/business'

const dateRange = ref([])
function onReset() {
  dateRange.value = []
  fetchChartData()
}

function handleSearch() {
  fetchChartData()
}

const tags = ref(['标签1', '标签2', '标签3', '标签4', '标签5', '标签6', '标签7', '标签8'])

const totalCount = ref(0)

const tableData = ref([])

const chartRef = ref<HTMLDivElement | null>(null)
let chartInstance: EChartsType | null = null

const chartRef2 = ref<HTMLDivElement | null>(null)
let chartInstance2: EChartsType | null = null

interface ActivityQueryParams {
  pageNum: number
  pageSize: number
  dateRange?: [string, string]
  params?: {
    beginTime?: string
    endTime?: string
  }
}

const fetchChartData = async () => {
  try {
    const token = getToken()
    const headers = token ? { 'Authorization': 'Bearer ' + token } : {}
    const queryParams: any = {
      pageNum: 1,
      pageSize: 10,
      _t: Date.now()
    }

    if (dateRange.value && dateRange.value.length === 2) {
      const start = (dateRange.value[0] as string).slice(0, 10) + ' 12:00:00'
      const end = (dateRange.value[1] as string).slice(0, 10) + ' 12:00:00'
      queryParams['dateRange[0]'] = start
      queryParams['dateRange[1]'] = end
      queryParams['params[beginTime]'] = start
      queryParams['params[endTime]'] = end
    }

    const response = await getActivityAnalysis(queryParams)

    if (response.data && response.code === 200 && Array.isArray(response.data)) {
      // 第一个图表（饼图）的数据
      const chart1Data = response.data.map(item => ({
        value: item.count,
        name: item.name
      }))
      totalCount.value = response.total

      if (chartInstance) {
        chartInstance.setOption({
          series: [
            {
              data: chart1Data
            }
          ]
        })
      }

      // 第二个图表（折线图）的数据
      const chart2XAxisData = response.data.map(item => item.name)
      const chart2SeriesData = response.data.map(item => item.available)

      if (chartInstance2) {
        chartInstance2.setOption({
          xAxis: {
            data: chart2XAxisData
          },
          series: [
            {
              data: chart2SeriesData
            }
          ]
        })
      }

      // 表格显示全部数据
      tableData.value = response.data

    } else {
      console.error('API 返回数据格式不正确或操作失败:', response.data)
    }
  } catch (error) {
    console.error('获取图表数据失败:', error)
    if (error.response && error.response.status === 401) {
      console.error('认证失败，请重新登录。')
    }
  }
}

onMounted(() => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    chartInstance.setOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: '0%',
        top: 'middle'
      },
      series: [
        {
          name: '活动分析',
          type: 'pie',
          radius: '60%',
          center: ['50%', '50%'],
          data: [],
          label: {
            formatter: '{b}'
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  }

  // 初始化第二个图表
  if (chartRef2.value) {
    chartInstance2 = echarts.init(chartRef2.value)
    chartInstance2.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line'
        }
      },
      legend: {
        bottom: '0%',
        left: 'center'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: ['抖音啊啊啊啊', 'sdadasd', 'dwd', '22', '接着骂啊', '阿萨', '123', '跟他', 'awda', 'xzc', 'k8', '6666', '43', '-1-1'],
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          min: 0,
          max: 1
        }
      ],
      series: [
        {
          name: '活动线索有效率',
          type: 'line',
          itemStyle: {
            color: '#409EFF'
          },
          data: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        }
      ]
    })
  }

  fetchChartData()
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  if (chartInstance2) {
    chartInstance2.dispose()
  }
})
</script> 